'''操作数据库'''
from peewee import *
import os
from dotenv import load_dotenv


load_dotenv()


mysql = MySQLDatabase(user=os.getenv("DB_USER"),
                      password=os.getenv("DB_PASSWORD"),
                      host=os.getenv("DB_HOST"),database=os.getenv("DB_NAME"))

class BaseModel(Model):
    class Meta:
        database = mysql

class CvvCardData(BaseModel):

    id = BigAutoField(primary_key=True)
    card_number = CharField(max_length=64)
    expiry_date = CharField(max_length=16)
    hold_name = CharField(max_length=128)
    status = IntegerField(default=0)
    user_id = BigIntegerField()
    create_time = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
    file_name = CharField(max_length=128)
    class Meta:
        table_name = 'cvv_card_data'
        # 如果需要更精确的控制，可以在这里添加表设置
        indexes = (
            (('user_id',), False),
        )
        table_settings = [
            'ENGINE=InnoDB',
            'DEFAULT CHARSET=utf8mb4',
            'COLLATE=utf8mb4_unicode_ci'
        ]


class CvvUser(BaseModel):
    id = BigAutoField(primary_key=True)
    username = CharField(max_length=64, unique=True)
    email = CharField(max_length=64, unique=True)
    salt = CharField(max_length=64)
    password = CharField(max_length=128)
    create_time = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
    status = IntegerField(default=1)
    error_count = IntegerField(default=0)
    update_time=DateTimeField()
    delete_flag=IntegerField(default=0)
    user_type=IntegerField(default=1)
    expiry_time=DateTimeField()
    query_count=IntegerField(default=9999)
    class Meta:
        table_name = 'cvv_user'
        table_settings = [
            'ENGINE=InnoDB',
            'DEFAULT CHARSET=utf8mb4',
            'COLLATE=utf8mb4_unicode_ci'
        ]

class CvvManatukuUser(BaseModel):

    id = BigAutoField(primary_key=True)
    card_number = CharField(max_length=64)
    gmo_token = TextField()
    mk_user = CharField(max_length=128)
    mk_ps = CharField(max_length=128)
    pn_session = TextField()
    pn_html = TextField()
    proxy_ip = CharField(max_length=16)
    class Meta:
        table_name = 'cvv_manatuku_user'

    table_settings = [
        'ENGINE=InnoDB',
        'DEFAULT CHARSET=utf8mb4',
        'COLLATE=utf8mb4_unicode_ci'
    ]

def setup_database():
    """初始化数据库和表"""
    mysql.connect()

    # 创建表
    tables = [CvvCardData, CvvUser,CvvManatukuUser]
    mysql.create_tables(tables, safe=True)

    print("数据库表创建完成")
    print("表设置: InnoDB 存储引擎, utf8mb4 字符集")

if __name__ == '__main__':
    setup_database()